package ihm.manes_ho.agenda;

import ihm.manes_ho.agenda.dialog.ArticleDialog;
import ihm.manes_ho.agenda.vo.ArticleVO;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Liste des courses 
 */
public class ListeDeCourses extends ListActivity {
	public static final String LOG_TAG = ListeDeCourses.class.toString();
	static final int ADD_DIALOG_ID = 0;
	static final int EDIT_DIALOG_ID = 1;	
	private static ArticleVO selectedArticle;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setListAdapter(new ArticleAdapter(this));
	}

	/**
	 * onCreateDialog - shows either one of the following dialogs:
	 * <p> 1. Dialog of adding an article
	 * <p> 2. Dialog of updating an article
	 * 
	 * <p>This method is only called the very FIRST time a dialog is opened
	 * <p> This callback method is passed the same ID that we passed to showDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case EDIT_DIALOG_ID:
			return new ArticleDialog(this, EDIT_DIALOG_ID, onOkClickListener); //call my dialog!
		case ADD_DIALOG_ID:
			return new ArticleDialog(this, ADD_DIALOG_ID, onOkClickListener);
		}
		return null;
	}

	/**
	 * This method is called every time a dialog is opened
	 */
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case EDIT_DIALOG_ID:
			((ArticleDialog) dialog).setData(selectedArticle);
			break;
		case ADD_DIALOG_ID:
			break;
		}
	}

	/**
	 * the callback is called when the user clicks the Ok button in the dialog (add/update)
	 */
	private ArticleDialog.OnOkClickListener onOkClickListener = 
		new ArticleDialog.OnOkClickListener() {

		//override the callback method
		@Override
		public void onOkClick(int type, String name, Integer quantity, Double price) {

			switch (type) {
			case EDIT_DIALOG_ID:
				//update name, number, price on the article list...
				selectedArticle.setName(name);
				selectedArticle.setQuantity(quantity);
				selectedArticle.setPrice(price);
				onContentChanged(); //update View
				break;

			case ADD_DIALOG_ID:
				ARTICLES.add(new ArticleVO(name, quantity, price));
				onContentChanged();
				break;
			}
		}
	};

	/**
	 * onCreateOptionsMenu - creating menu "add" / "remove all" for the "liste de courses"
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_remove_all:
			AlertDialog.Builder builder = new AlertDialog.Builder(ListeDeCourses.this);
            builder.setTitle(getResources().getString(R.string.txt_confirmation));
            builder.setMessage(getResources().getString(R.string.txt_confirm_remove_all_articles));
            builder.setPositiveButton(getResources().getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	ARTICLES.clear(); //remove all
        			onContentChanged(); //update view                          
                }                        
            });
            builder.setNegativeButton(getResources().getString(R.string.btn_cancel), null);
            builder.show();				
			break;
			
		case R.id.menu_add: 
			showDialog(ADD_DIALOG_ID); //show add dialog
			break;
		}
		return true;
	}
	
	/**
	 * ARTICLES - hard-coded data
	 */
	private static List<ArticleVO> ARTICLES = new ArrayList<ArticleVO>(
			Arrays.asList(
					new ArticleVO("Pain", 1, 1.23),
					new ArticleVO("Vin", 2, 2.34),
					new ArticleVO("Boursin", 3, 3.45),
					new ArticleVO("Baguette", 4, 4.56),
					new ArticleVO("Fromage", 5, 5.67),
					new ArticleVO("Poulet", 6, 6.78)
			));
	
	/**
	 * defines ArticleAdapter class --- static nested-class
	 * <p> This apdater is passed to the list activity "ListeDeCourses"
	 */
	private static class ArticleAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Bitmap icon_check;
		private Bitmap icon_box;
		private Bitmap icon_remove;
		private Bitmap icon_edit;

		public ArticleAdapter(Context context) {
			mInflater = LayoutInflater.from(context);

			// Icons bound to the rows.
			icon_check = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_check);
			icon_box = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_box);
			icon_remove = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_remove);
			icon_edit = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_edit);
		}

		@Override
		public int getCount() {
			return ARTICLES.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid unnecessary calls
			// to findViewById() on each row.
			final ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item, null);

				holder = new ViewHolder();
				holder.text_name = (TextView) convertView.findViewById(R.id.text_name);
				holder.text_quantity = (TextView) convertView.findViewById(R.id.text_quantity);
				holder.text_price = (TextView) convertView.findViewById(R.id.text_price);
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);
				holder.icon_remove = (ImageView) convertView.findViewById(R.id.icon_remove);
				holder.icon_edit = (ImageView) convertView.findViewById(R.id.icon_edit);

				//set viewholder as a tag
				convertView.setTag(holder);
			} else {
				//get viewholder
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			holder.text_name.setText(ARTICLES.get(position).getName());
			holder.text_quantity.setText(String.valueOf(ARTICLES.get(position).getQuantity()));
			holder.text_price.setText(String.valueOf(ARTICLES.get(position).getPrice()));
			holder.icon.setImageBitmap((position & 1) == 1 ? icon_check : icon_box);
			holder.icon_remove.setImageBitmap(icon_remove);
			holder.icon_edit.setImageBitmap(icon_edit);
			holder.position = position;


			// set listener
			holder.icon_edit.setOnClickListener(new OnActionClickListener(1, convertView));
			holder.icon_remove.setOnClickListener(new OnActionClickListener(2, convertView));
			return convertView;
		}
		
		static class OnActionClickListener implements OnClickListener {
			static final int EDIT_ACTION = 1;
			static final int REMOVE_ACTION = 2;
			int actionType;
			View articleView;

			public OnActionClickListener( int actionType, View articleView) {
				this.actionType = actionType;
				this.articleView = articleView;
			}
			
			@Override
			public void onClick(final View v) {
				final ViewHolder holder = (ViewHolder) articleView.getTag();
				if (holder != null) {
					switch (actionType) {
					case EDIT_ACTION:
						selectedArticle = ARTICLES.get(holder.position);
						Log.v(LOG_TAG, selectedArticle.toString());
						((Activity) v.getContext()).showDialog(EDIT_DIALOG_ID); //show edit dialog
						break;

					case REMOVE_ACTION:
						AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			            builder.setTitle(v.getContext().getResources().getString(R.string.txt_confirmation));
			            builder.setMessage(v.getContext().getResources().getString(R.string.txt_confirm_remove_an_article));
			            builder.setPositiveButton(v.getContext().getResources().getString(R.string.btn_ok), 
			            		new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int which) {
			                	ARTICLES.remove(holder.position);
								((Activity) v.getContext()).onContentChanged(); //update view                          
			                }
			            });
			            builder.setNegativeButton(v.getContext().getResources().getString(R.string.btn_cancel), null);
			            builder.show();						
						break;
					}
				}
			}
		}
		
		static class ViewHolder {
			int position; //first position = 0
			TextView text_name;
			TextView text_quantity;
			TextView text_price;
			ImageView icon;
			ImageView icon_remove;
			ImageView icon_edit;
		}
	} // end definition of the ArticleAdapter static nested-class
}
